@file:OptIn(ExperimentalMaterial3Api::class)

package com.auto.base.widget

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp


@Composable
fun <T> RefreshLayout(
    modifier: Modifier = Modifier,
    beans: List<T>,
    isLoading: Boolean,
    onLoadMore: () -> Unit,
    itemContent: @Composable (T) -> Unit,
    loadingContent: @Composable () -> Unit = {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.Center
        ) {
            CircularProgressIndicator(modifier = Modifier.size(20.dp))
            Spacer(modifier = Modifier.width(8.dp))
            Text("加载中...", style = MaterialTheme.typography.bodySmall)
        }
    }
) {
    val listState = rememberLazyListState()
    // 下拉刷新状态
//    val pullRefreshState = rememberPullRefreshState(
//        refreshing = isRefreshing,
//        onRefresh = {
//            isRefreshing = true
//            // 模拟加载
//            LaunchedEffect(Unit) {
//                kotlinx.coroutines.delay(1500)
//                isRefreshing = false
//            }
//        }
//    )
    // 监听滑动到末尾
    LaunchedEffect(listState, isLoading, beans.size) {
        snapshotFlow {
            val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
            lastVisible >= beans.lastIndex && !isLoading
        }.collect { shouldLoad ->
            if (shouldLoad) onLoadMore()
        }
    }

    LazyColumn(
        state = listState
    ) {
        items(beans) { item ->
            itemContent(item)
        }
        if (isLoading) {
            item {
                loadingContent()
            }
        }
    }
}